const express = require('express');
const router = express.Router();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys")
const User = require("../../models/Users");
const passport = require("passport");

// router.get('/test', (req, res) => {
//   res.json({msg:"login sucess!"});
// });

//注册
router.post("/register", (req, res) => {
  // console.log(req.body);
  User.findOne({email:req.body.email})
      .then((user) => {
        if(user){
          return res.status(404).json({email:"邮箱已经注册"})
          }else{
            const newUser = new User({
              name: req.body.name,
              email:req.body.email,
              // acatar,
              password:req.body.password,
              identity: req.body.identity
          })
          //密码加密
          bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.password, salt, (err, hash) =>{
              if(err) throw err;
              newUser.password = hash;
              newUser.save()
                     .then(user => res.json(user))
                     .catch(err => console.log(err));
            })
          })
        }
      })

});

//登录
router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  User.findOne({email})
      .then(user => {
        if(!user){
          return res.status(404).json({email:"用户不存在！"});
        }
      })

      bcrypt.compare(password, user.password)
            .then(isMatch => {
              if(isMatch){
                const rule = {id: user.id, name: user.name};
                //规则 加密文字 过期时间 箭头函数
                jwt.sign("rule", "keys.secretOrKey", "expiresIn:3600", (err, token) => {
                  if(err) throw err;
                  res.json({
                    success: true,
                    token: "Bearer " + token
                  })
                })
                // res.json({msg:"sucess"});
              }else{
                return res.status(404).json({password:"密码错误！"});
              }
            })
})

//$route GET api/users/current
//@desc return current user
//@access Private
router.get("/current", passport.authenticate("jwt", {session:false}), (req, res) => {
  res.json({
    id: "req.user.id",
    name: "req.user.name",
    email: "req.user.email",
    identity: "req.user.identity"
  });
})

module.exports = router;